//
//  Miscellaneous.swift
//  Trans
//
//  Created by zcj on 2025/3/20.
//

import Foundation
import os.log

func error_log(_ msg:String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line){
    os_log(.error, "file:\(file)->function:\(function)-> line:\(line) \(msg)")
}

func warn_log(_ msg:String,file: StaticString = #file, function: StaticString = #function, line: UInt = #line){
    os_log(.debug, "file:\(file)->function:\(function)-> line:\(line) \(msg)")
}

func info_log(_ msg:String,file:StaticString = #file, function: StaticString = #function, line: UInt = #line){
    os_log(.info,"file:\(file)->function:\(function)-> line:\(line) \(msg)")
}


func getipFromEndpoint(addr:String) -> String{
    let strArr = addr.split(separator: ":")
    return String(strArr[0])
    
}

func OnceTimeReqType() -> Array<UINT32>{
    return [FILE_CANCEL,FILE_STOP,FILE_RESUME,RECONNECT]
//    return [RECONNECT]
}


func getUdpPort()->UInt16{
    if let path = Bundle.main.path(forResource: "properties", ofType: "plist"),
       let dict = NSDictionary(contentsOfFile: path) as? [String: Any] {
        // 现在你可以通过键来访问plist中的值了
        if let port = dict["UDPPort"] as? UInt16 {
            return port
        }
    } else {
        print("Plist file not found")
        
    }
    return 13532
}

func getTcpPort()-> UInt16{
    if let path = Bundle.main.path(forResource: "properties", ofType: "plist"),
       let dict = NSDictionary(contentsOfFile: path) as? [String: Any] {
        // 现在你可以通过键来访问plist中的值了
        if let port = dict["TCPPort"] as? UInt16 {
            return port
        }
    } else {
        print("Plist file not found")
        
    }
    return 13531
}

func size2StrFormat(dnum:Double) ->String{
    if dnum >= GBSize {
        return String.init(format: "%.2fGB", arguments: [dnum/GBSize])
    }else if dnum >= MBSize{
        return String.init(format: "%.2fMB", arguments: [dnum/MBSize])
    }else if dnum >= KBSize{
        return String.init(format: "%.2fKB", arguments: [dnum/KBSize])
    }
    return String.init(format: "%.2fB", arguments: [dnum])
}

func str2SizeFormat(str:String) -> FSIZE{
    if str.count < 2{
        return 0
    }
    let startIndex = str.startIndex
    let endIndex = str.index(startIndex, offsetBy: str.count-1)
    let sizeStr = str[startIndex..<endIndex]
    if let num = FSIZE(sizeStr){
        if str.last == "M"{
            return num * UInt64(MBSize)
        }else if str.last == "G"{
            return num * UInt64(GBSize)
        }
    }else{
        print("str2SizeFormat : transfor failed")
    }
    return 0
}

func getFileId(remoteIp:String,localIp:String,fileName:String) -> FileId{
    let tempStr = "\(remoteIp)+\(localIp)+\(fileName)"
    return FileId(tempStr.hashValue)
}

public func getBroadcastAddresses() -> [String] {
    var broadcastAddresses: [String] = []
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    
    guard getifaddrs(&ifaddr) == 0 else { return [] }
    var ptr = ifaddr
    
    while ptr != nil {
        defer { ptr = ptr?.pointee.ifa_next }
        
        let interface = ptr?.pointee
        let addrFamily = interface?.ifa_addr.pointee.sa_family
        
        if addrFamily == UInt8(AF_INET) {
            let broadcastAddr = interface?.ifa_dstaddr
            if broadcastAddr != nil {
                var addr = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(broadcastAddr, socklen_t(interface!.ifa_addr.pointee.sa_len), &addr, socklen_t(NI_MAXHOST), nil, socklen_t(0), NI_NUMERICHOST)
                let broadcastAddress = String(cString: addr)
                if(broadcastAddress != "127.0.0.1"){
                    broadcastAddresses.append(broadcastAddress)
                }
                
            }
        }
    }
    
    freeifaddrs(ifaddr)
    return broadcastAddresses
}
